import { ref, computed, reactive } from 'vue';

class VMControl {
    constructor(apiPrefix, pk, searchKey = 'name') {
        this.apiPrefix = apiPrefix;
        this.pk = pk;
        this.searchKey = searchKey;
        this.rawModel = {};
        // Model list
        this.modelList = ref([]);
        // Search keyword
        this.searchKeyword = ref('');
        // Show modal flag
        this.showModal = ref(false);
        this.showMenu = ref(false);
        // Modal mode: add or edit
        this.modalMode = ref('add');
        // Current model data
        this.currentModel = reactive({});
        this.filteredModels = ref([]);

        this.fileList = {};
    }

    openMenu() {
        this.showMenu.value = true;
    }
    openMenuModel(model) {
        this.setCurrentModel(model);
        this.showMenu.value = true;
    }
    closeMenu() {
        this.showMenu.value = false;
    }

    closePopup() {
        this.showModal.value = false;
    }

    openPopup() {
        this.showModal.value = true;
    }

    setCurrentModel(model) {
        Object.assign(this.currentModel, model);
    }

    handleBack() {
        uni.navigateBack();
    }

    // Add model
    handleAdd() {
        this.modalMode.value = 'add';
        Object.assign(this.currentModel, this.rawModel);
        this.openPopup();
    }

    // Edit model
    handleEdit() {
        this.modalMode.value = 'edit';
        this.openPopup();
    }

    handleEditModel(model) {
        this.setCurrentModel(model);
        this.handleEdit();
    }

    handleSearch() {
        if (!this.searchKeyword.value) {
            this.filteredModels.value = this.modelList.value;
        }
        else {
            this.filteredModels.value = this.modelList.value.filter(model =>
                model[this.searchKey] && model[this.searchKey].toLowerCase().includes(this.searchKeyword.value.toLowerCase())
            );
        }
    }

    handleDeleteModel(model) {
        this.setCurrentModel(model);
        this.handleDelete();
    }

    // Delete model
    handleDelete() {
        this.closeMenu();
        var id = this.currentModel[this.pk];
        uni.showModal({
            title: '确认删除',
            content: `确定要删除"${this.currentModel.name}"吗？`,
            success: async (res) => {
                if (res.confirm) {
                    const index = this.modelList.value.findIndex(m => m[this.pk] === id);
                    if (index !== -1) {
                        const im = await J.callApiAsync(
                            `${this.apiPrefix}.delete_by_id`, { id: id });
                        if (im.success) {
                            this.modelList.value.splice(index, 1);
                            uni.showToast({ title: '删除成功', icon: 'success' });
                        } else {
                            uni.showToast({ title: '删除失败: ' + (im.msg || '未知错误'), icon: 'error' });
                            console.log('删除失败:', im);
                        }
                    }
                    // I.closeMenu(); // Removed as it's specific to drama context
                    // this.closePopup();
                }
            }
        });
    }

    // Submit form (add or edit)
    async handleSubmit() {
        var id = this.currentModel[this.pk];

        // 先对文件上传做预处理，上传的文件路径以逗号分隔存储
        for (let field in this.fileList[id]) {
            if (this.fileList[id][field] && this.fileList[id][field].value.length > 0) {
                this.currentModel[field] = this.fileList[id][field].value.map(file => file.url.split('filename=')[1]).join(',');
            } else {
                this.currentModel[field] = '';
            }
        }


        if (this.modalMode.value === 'add') {
            const im = await J.callApiAsync(
                `${this.apiPrefix}.add`,
                { model: { ...this.currentModel } });
            if (im.success) {
                this.setCurrentModel(im.data);
                this.modelList.value.push({ ...this.currentModel });
                uni.showToast({ title: '添加成功', icon: 'success' });
            } else {
                console.error('添加失败:', im);
            }
        } else {
            const im = await J.callApiAsync(
                `${this.apiPrefix}.update_by_id`, {
                id: this.currentModel[this.pk],
                model: { ...this.currentModel }
            });
            if (im.success) {
                const index = this.modelList.value.findIndex(m => m[this.pk] === this.currentModel[this.pk]);
                if (index !== -1) {
                    this.modelList.value[index] = { ...this.currentModel };
                }
                uni.showToast({ title: '更新成功', icon: 'success' });
            } else {
                console.error('更新失败:', im);
            }
        }
        this.closePopup();
    }

    async loadMeta() {
        const im = await J.callApiAsync(
            `${this.apiPrefix}.get_meta`, {});
        if (im.success) {
            this.rawModel = im.data;
            this.rawModel[this.pk] = -1; // Default ID for new models
            Object.assign(this.currentModel, this.rawModel);
        } else {
            console.error('获取元数据失败:', im);
        }
        return im;
    }

    // Load model data
    async loadModels(params = {}, options = {}) {
        const res = await J.callApiAsync(
            `${this.apiPrefix}.get_list`, params);
        if (res.success) {
            this.modelList.value = res.data;
            if (options.fileFields)
                this.initFileList(options.fileFields);
            this.filteredModels.value = this.modelList.value;
        } else {
            console.error(`加载数据失败:`, res);
            this.modelList.value = [];
            this.filteredModels.value = [];
        }
    }

    initFileList(fields) {

        if (!fields) {
            return;
        }

        this.modelList.value.map(model => {
            var file = this.fileList[model[this.pk]] = {};
            fields.forEach(field => {
                if (model.hasOwnProperty(field)) {
                    file[field] = ref([]);
                    file[field].value = model[field] ? model[field].split(",").map(url => ({ url: J.formatFileUrl(url) })) : [];
                }
            });
        });
    }

    async handleFileRead(field, event, count = 1) {
        var id = this.currentModel[this.pk];
        // 依据 this.fileList 对应 field 键进行赋值，核心是 event.file，还有 status 和 message

        var files = this.fileList[id][field].value;
        if (files.length >= count) {
            uni.showToast({ title: `最多只能上传${count}个文件`, icon: 'none' });
            return;
        } else {
            // 开始
            files.push({
                ...event.file,
                status: 'uploading',
                message: '上传中',
            });
            // 上传
            var im = await J.callUploadAsync(event.file.url, { keep: false, override: false });

            if (im.success) {
                console.log('上传成功:', im.data);
                var len1 = files.length;
                files[len1 - 1] = {
                    ...event.file,
                    status: 'success',
                    message: '',
                    url: J.formatFileUrl(im.data.filename),
                };
            } else {
                console.log('上传失败:' + im.msg);
            }

        }
    }
    handleFileDelete(field, event, count) {
        var id = this.currentModel[this.pk];
        this.fileList[id][field].value.splice(event.index, 1);
    }
}

export default VMControl;